package com.leetcode.partition4;

import java.io.*;

/**
 * @author `RKC`
 * @date 2022/1/2 21:44
 */
public class LC390消除游戏 {

    private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    private static final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        int n = Integer.parseInt(reader.readLine());
        writer.write(lastRemaining(n) + "\n");
        writer.flush();
    }

    public static int lastRemaining(int n) {
        //首项、轮次、当前还有多少个数，公差
        int a1 = 1, k = 0, cnt = n, d = 1;
        while (cnt > 1) {
            if ((k & 1) == 0) {
                //正向删除，首项（左边界）肯定会被删除，寻找下一个首项
                a1 = a1 + d;
            } else {
                //反向删除，如果剩余的数是偶数则不会改变当前的首项（左边界），否则会删除掉当前的首项，寻找下一个首项
                a1 = (cnt & 1) == 0 ? a1 : a1 + d;
            }
            k++;
            cnt >>= 1;
            d <<= 1;
        }
        return a1;
    }
}
